package com.beverages.individual.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beverages.individual.common.Constants;
import com.beverages.individual.common.Result;
import com.beverages.individual.entity.Individual;
import com.beverages.individual.entity.dto.IndividualDTO;
import com.beverages.individual.entity.dto.IndividualPasswordDTO;
import com.beverages.individual.mapper.IndividualMapper;
import com.beverages.individual.service.IIndividualService;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;



import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xxxx
 * @since 2022-01-26
 */
@RestController
@RequestMapping("/customer/individual")
public class IndividualController {

    @Resource
    private IIndividualService individualService;

    @Autowired
    private IndividualMapper individualMapper;

    @ApiOperation(
            value = "登录",
            notes = "只传值：\n" +
                    "1: username —— 账户\n" +
                    "2: password —— 密码\n",
            response = Result.class,
            tags = {"登录"}
    )
    @PostMapping("/login")
    public Result login(@RequestBody IndividualDTO individualDTO) {
        String username = individualDTO.getUsername();
        String password = individualDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        IndividualDTO dto = individualService.login(individualDTO);
        return Result.success(dto);
    }

    @ApiOperation(
            value = "注册",
            notes = "只传值：\n" +
                    "1: username —— 账户\n" +
                    "2: password —— 密码\n" +
                    "注册完后立刻让顾客修改个人信息。",
            response = Result.class,
            tags = {"注册"}
    )
    @PostMapping("/register")
    public Result register(@RequestBody IndividualDTO individualDTO) {
        String username = individualDTO.getUsername();
        String password = individualDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        return Result.success(individualService.register(individualDTO));
    }

    @ApiOperation(
            value = "修改个人信息",
            notes = "必须传值：\n" +
                    "1: id \n" +
                    "2: nickname —— 昵称\n" +
                    "3: phone —— 手机\n" +
                    "4: avatarId —— 头像id\n" +
                    "5: sex —— 性别，\"男\" 或者 \"女\" \n" +
                    "6: role —— 角色，\"商家\" 或者 \"顾客\" ，这个不能更改，但也要传值\n",
            response = Result.class,
            tags = {"修改个人信息"}
    )
    @PostMapping("/modify")
    public Result modifyIndividualInformation(@RequestBody IndividualDTO individualDTO){
        Individual individual = new Individual();

        individual.setId(individualDTO.getId());
        individual.setNickname(individualDTO.getNickname());
        individual.setPhone(individualDTO.getPhone());
        individual.setAvatarId(individualDTO.getAvatarId());

        Integer sexInteger = 0;
        switch (individualDTO.getSex()){
            case "男":
                sexInteger = 1;
                break;
            case "女":
                sexInteger = 2;
                break;
            case "其他":
                sexInteger = 3;
                break;
        }
        individual.setSex(sexInteger);

        Integer roleInteger = -1;
        switch (individualDTO.getRole()){
            case "商家":
                roleInteger = 0;
                break;
            case "顾客":
                roleInteger = 1;
                break;
        }
        individual.setRole(roleInteger);

        individualService.updateById(individual);

        return Result.success();
    }

    // 新增或者更新
    @ApiOperation(
            value = "新增用户",
            notes = "尚未完善\n",
            response = Result.class,
            tags = {"这些接口不用管"}
    )
    @PostMapping
    public Result save(@RequestBody Individual individual) {
        if (individual.getId() == null && individual.getPassword() == null) {  // 新增用户默认密码
            individual.setPassword( SecureUtil.md5("123"));
        }
        return Result.success(individualService.saveOrUpdate(individual));
    }

    @ApiOperation(
            value = "修改密码",
            notes = "必须传值：\n" +
                    "1: username —— 用户名；\n" +
                    "2: password —— 原密码；\n" +
                    "3: newPassword —— 新密码。\n",
            response = Result.class,
            tags = {"修改密码"}
    )
    @PostMapping("/password")
    public Result password(@RequestBody IndividualPasswordDTO individualPasswordDTO) {
        individualPasswordDTO.setPassword(SecureUtil.md5(individualPasswordDTO.getPassword()));
        individualPasswordDTO.setNewPassword(SecureUtil.md5(individualPasswordDTO.getNewPassword()));
        individualService.updatePassword(individualPasswordDTO);
        return Result.success();
    }

    @ApiOperation(
            value = "删除用户",
            response = Result.class,
            tags = {"这些接口不用管"}
    )
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(individualService.removeById(id));
    }

    @ApiOperation(
            value = "批量删除用户",
            response = Result.class,
            tags = {"这些接口不用管"}
    )
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(individualService.removeByIds(ids));
    }

    @ApiOperation(
            value = "查找所有顾客",
            response = Result.class,
            tags = {"这些接口不用管"}
    )
    @GetMapping
    public Result findAll() {
        return Result.success(individualService.list());
    }

    @ApiOperation(
            value = "根据角色查找用户",
            response = Result.class,
            tags = {"这些接口不用管"}
    )
    @GetMapping("/role/{role}")
    public Result findIndividualsByRole(@PathVariable String role) {
        QueryWrapper<Individual> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role", role);
        List<Individual> list = individualService.list(queryWrapper);
        return Result.success(list);
    }

    @ApiOperation(
            value = "根据id查询顾客",
            response = Result.class,
            tags = {"这些接口不用管"}
    )
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(individualService.getById(id));
    }

    @ApiOperation(
            value = "账号查询",
            notes = "必须传参：\n" +
                    "username   (String)\n",
            response = Result.class,
            tags = {"根据账号查找顾客"}
    )
    @GetMapping("/username/{username}")
    public Result findByUsername(@PathVariable String username) {
        QueryWrapper<Individual> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return Result.success(individualService.getOne(queryWrapper));
    }

    @ApiOperation(
            value = "根据顾客id查找顾客",
            notes = "必须传参：\n" +
                    "individualId   (Integer)\n",
            response = Result.class,
            tags = {"这些接口不用管"}
    )
    @GetMapping("/id/{individualId}")
    public Result getIndividualById(@PathVariable Integer individualId) {
        return Result.success(individualService.convertIndividualEntityToIndividualDTO(individualService.getById(individualId)));
    }

    @ApiOperation(
            value = "账号充值",
            notes = "必须传参：\n" +
                    "1: individualId   (Integer)\n" +
                    "2: amount   (BigDecimal)\n",
            response = Result.class,
            tags = {"充值"}
    )
    @GetMapping("/recharge")
    public Result recharge(@RequestParam Integer individualId,
                           @RequestParam BigDecimal amount){
        Individual individual = individualService.getById(individualId);
        BigDecimal individualInitialBalance = individual.getBalance();
        individual.setBalance(individualInitialBalance.add(amount));
        individualMapper.updateById(individual);
        return Result.success();
    }


}


